package sdu.icat.pj.listener;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import sdu.icat.pj.support.Constants;
import sdu.icat.pj.util.CacheUtil;

public class SessionListener implements HttpSessionListener {

    private Logger logger = LogManager.getLogger(SessionListener.class);
    
    @Override
    public void sessionCreated(HttpSessionEvent se) {
	HttpSession session = se.getSession();
	session.setAttribute(Constants.WEBTHEME, "default");
	logger.info("创建了一个Session连接：["+session.getId()+"]");
	CacheUtil.getCache().sadd(Constants.ALLUSER_NUMBER, session.getId());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
	HttpSession session = se.getSession();
	if(getAllUserNumber() > 0) {
	    logger.info("销毁了一个Session连接：["+session.getId()+"]");
	}
	session.removeAttribute(Constants.CURRENT_USER);
	CacheUtil.getCache().sdel(Constants.ALLUSER_NUMBER, session.getId());
    }

    public Integer getAllUserNumber() {
	return CacheUtil.getCache().sall(Constants.ALLUSER_NUMBER).size();
    }
}
